from flask import render_template, request, redirect, url_for, session, jsonify
from werkzeug.security import check_password_hash

from moldels import db
from moldels.index import Users, Commod
from views import admin_blu


@admin_blu.route("/admin")
def admin_index():
    return redirect(url_for(admin_login))


@admin_blu.route("/admin/login", methods=["POST", "GET"])
def admin_login():
    type = request.method

    if type == "GET":
        return render_template("admin/login.html")

    else:
        phone = request.json.get("user_name")
        password = request.json.get("user_password")

        # 数据库查询

        user = db.session.query(Users).filter(Users.mobile == phone).first()

        if user and check_password_hash(user.password_hash, password):

            if not user.is_admin:
                ret = {
                    "errno": '1002',
                    "errmsg": "权限不够"
                }

                return jsonify(ret)
            # 保持登录状态
            session["user_id"] = user.id

            ret = {
                "errno": "0",
                "errmsg": "成功"
            }
        else:
            ret = {
                "errno": "101",
                "errmsg": "用户名密码错误"
            }

    return jsonify(ret)


@admin_blu.route("/admin/index")
def index():
    user_id = session.get("user_id")

    if not user_id:
        return redirect("/admin/login")

    user = db.session.query(Users).filter(Users.id == user_id).first()
    print(user_id)
    print(user)
    if not user.is_admin:
        return redirect("/admin/login")

    page = request.args.get("page",1)

    users = db.session.query(Users).paginate(page=int(page),per_page=4,error_out=False)

    users.count = db.session.query(Users).count()

    users.comd_count = db.session.query(Commod).count()

    return render_template("admin/index.html", users=users, user=user)
